import ProForm, { ProFormDigit, ProFormSwitch, ProFormText } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import { FooterToolbar } from '@ant-design/pro-layout';
import { Card, Form, message, TreeSelect } from 'antd';
import React, { useEffect, useState } from 'react';
import { useHistory, useParams } from 'react-router-dom';

import { IMenu } from '@/models/user';
import { addMenus, getMenu, getMenus, updateMenus } from '@/services/system/menu';
import { flatToNest } from '@/utils';

import { IParams } from './type';

export default () => {
  const history = useHistory();
  const params: IParams = useParams();

  const [menus, setMenus] = useState([]);

  useEffect(() => {
    fetchMenus();
  }, []);

  async function fetchMenus() {
    const { data } = await getMenus();
    const menus = flatToNest(
      data?.map((v: IMenu) => ({
        label: v.title,
        value: v.id,
        id: v.id,
        parent_id: v.parent_id,
      })) || [],
    );
    menus.unshift({ label: 'EP', value: 0 });
    setMenus(menus);
  }

  return (
    <PageContainer onBack={() => history.push('/system/menu')}>
      <Card>
        <ProForm
          onFinish={async (values) => {
            const { message: msg, code, data } = params.id
              ? await updateMenus({
                  menu_id: +params.id,
                  ...values,
                })
              : await addMenus(values);
            if (code === 2000) {
              message.success(msg);
              history.push(`/system/menu/detail/${data.menu_id}`);
            } else {
              message.error(msg);
            }
          }}
          request={async () => {
            if (params.id) {
              const { data } = await getMenu(+params.id);
              return data;
            }
            return {
              show: true,
              order: 0,
            };
          }}
          submitter={{
            resetButtonProps: {
              style: {
                display: 'none',
              },
            },
            render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,
          }}>
          <ProFormText
            width="lg"
            name="title"
            label="菜单名称"
            rules={[{ required: true }]}
          />
          <ProFormText width="lg" name="code" label="code" rules={[{ required: true }]} />
          <Form.Item name="parent_id" label="上级菜单" className="width-lg">
            <TreeSelect treeData={menus} treeDefaultExpandAll />
          </Form.Item>
          <ProForm.Group>
            <ProFormText width="lg" name="path" label="路径" />
            <ProFormText width="lg" name="redirect" label="重定向" />
          </ProForm.Group>
          <ProFormText width="lg" name="icon" label="图标" />
          <ProFormSwitch name="show" label="是否展示" />
          <ProFormDigit width="lg" name="order" label="排序" min={0} max={10} />
        </ProForm>
      </Card>
    </PageContainer>
  );
};
